<?php

namespace Admin\Controller;

use Admin\Controller\CommonController;
use Usap\Service\Service;

/**
 *
 */
class StatisticsController extends CommonController
{

    /**
     * 实时数据统计图
     */
    public function view()
    {
        $devices_service = Service::instance()->find('devices', 'devices');
        $where = 1;
        $device_list = $devices_service->getDeviceList($where);
        $ycount = 0;
        $wcount = 0;
        $qcount = 0;
        $vid = [];
        $wid = [];
        $qid = [];
        foreach ($device_list['list'] as $value) {
            if ($value['device_type'] == '6') {
                $ycount++;
                $vid[] = $value['device_id'];
                //烟感
            } elseif ($value['device_type'] == '7') {
                $wcount++;
                $wid[] = $value['device_id'];
                //温感
            } else {
                $qcount++;
                $qid[] = $value['device_id'];
                //气感
            }
        }
        $devices = [
            [
                'value' => $ycount,
                'name' => '烟感'
            ],
            [
                'value' => $wcount,
                'name' => '温感',
            ],
            [
                'value' => $qcount,
                'name' => '气感',
            ]
        ];
        $alarms_service = Service::instance()->find('common', 'alarms');

        $alarm_list = $alarms_service->getAlarmsList($where);
        $avnum = 0;
        $awnum = 0;
        $aqnum = 0;

        $live_num = 0;//
        $demo_num = 0;
        $real_num = 0;

        //初始日期
        //获取7天数据
        $day = date('d');
        $year = date('Y');
        $moth = date('m');
        $date = [];
        $num = $pr = $er = 0;
        if ($day < 10) {
            $day = substr($day, 1, 1);
        }
        if ($day <= 7) {
            $num = getMonthLastDay($moth - 1, $year); //上个月总天数
            $pr = 7 - $day;
        } else {
            $er = $day - 7;
        }
        for ($i = $day; $i > $er; $i--) {
            if ($i < 10) {
                $d = date('Y-m') . '-0' . $i;
            } else {
                $d = date('Y-m') . '-' . $i;
            }
            $date[$d] = 0;
        }
        if ($pr > 0) {
            $moth = $moth - 1;
            for ($i = $num; $i > $num - $pr; $i--) {
                if ($moth < 10) {
                    $d = date('Y') . '-0' . $moth . '-' . $i;
                } else {
                    $d = date('Y') . '-' . $moth . '-' . $i;
                }
                $date[$d] = 0;
            }
        }
        foreach ($alarm_list['list'] as $value) {
            if (in_array($value['device_id'], $vid)) {
                //烟感报警数量avnum
                $avnum++;
            } elseif (in_array($value['device_id'], $wid)) {
                //温感报警数量awnum
                $awnum++;
            } elseif (in_array($value['device_id'], $qid)) {
                //气感报警数量aqnum
                $aqnum++;
            }
            if ($value['status'] == 1) {
                if ($value['alarm_type'] == 1) {
                    $demo_num++;
                    //演示
                } elseif ($value['alarm_type'] == 2) {
                    //日常
                    $live_num++;
                } elseif ($value['alarm_type'] == 3) {
                    //真实
                    $real_num++;
                }
            }
            $arr[date('Y-m-d', $value['created_time'])][] = $value;
        }
        $dateData = [];
        foreach ($date as $key => $vv) {
            if (isset($arr[$key])) {
                $res[0] = $key;
                $res[1] = count($arr[$key]);
            } else {
                $res[0] = $key;
                $res[1] = 0;
            }
            $dateData[] = $res;
        }
        $alarm = [
            [
                'value' => $avnum,
                'name' => '烟感',
            ],
            [
                'value' => $awnum,
                'name' => '温感',
            ],
            [
                'value' => $aqnum,
                'name' => '气感',
            ]
        ];
        $handle = [
            [
                'value' => $live_num,
                'name' => '日常',
            ],
            [
                'value' => $demo_num,
                'name' => '演示',
            ],
            [
                'value' => $real_num,
                'name' => '真实',
            ],
            [
                'value' => $live_num,
                'name' => '其他',
            ],
        ];
        $timeData = [];
        $timelist = $alarms_service->getAlarmsByHour();
        if ($timelist) {
            for ($i = 0; $i < 24; $i += 2) {
                $total = 0;
                foreach ($timelist as $vv) {
                    if ($vv['h'] > $i && $vv['h'] < $i + 2) {
                        $total += $vv['total'];
                    }
                }
                $timeData[] = [$i, $total];
            }
        } else {
            for ($i = 0; $i < 24; $i += 2) {
                $timeData[] = [$i, 0];
            }
        }

        $this->assign('device', 'sdsd');
        $this->assign('devices', $devices);
        $this->assign('alarm', $alarm);
        $this->assign('handle', $handle);
        $this->assign('timeData', $timeData);
        $this->assign('dateData', $dateData);
        $this->display('view');
    }

    public function maps()
    {
        $this->display('maps');
    }

    /**
     * 警报信息列表
     */
    public function alarms($page = 1, $rows = 20, $sort = 'alarm_id', $order = 'desc')
    {
        $alarms_service = Service::instance()->find('common', 'alarms');
        $devices_service = Service::instance()->find('devices', 'devices');
        //获取设备类别配置
        $device_categroy_config = $devices_service->getDeviceCategoryConfig();
        if (IS_POST) {
            $request = I('request.');
            $where = 1;
            if ($request['keyword']) {
                $keyword = $request['keyword'];
                $keyword_type = $request['keyword_type'];
                if ($keyword_type == 1) {
                    $where .= " and a.codeserial like '%$keyword%'";
                } elseif ($keyword_type == 2) {
                    $where .= " and  b.device_address like '%$keyword%'";
                } else {
                    $where .= " and a.codeserial like '%$keyword%' or  b.device_address like '%$keyword%'";
                }
            }
            if ($request['start_date']) {
                $start_date = strtotime($request['start_date']);
                $where .= " and a.created_time >= '$start_date'";
            }
            if ($request['end_date']) {
                $end_date = strtotime($request['end_date']);
                $where .= " and a.created_time <= '$end_date'";
            }
            $where .= " and a.status =0";
            $alarm_list = $alarms_service->getAlarmsList($where, $page, $rows, $sort, $order);
            $list = [];
            if ($alarm_list['count'] > 0) {
                foreach ($alarm_list['list'] as $value) {
                    $codeserial = $value['codeserial'];
                    $res['device_category'] = $device_categroy_config[$value['device_category']];
                    $res['device_address'] = $value['device_address'];//设备安装地址
                    $res['status'] = $value['status'] == 0 ? '<span style="color: red">未处置</span>' : '<span style="color: green">已处置</span>';
                    $res['alarms_times'] = $value['alarms_times'] ? $value['alarms_times'] : '1';
                    $res['id'] = $value['alarm_id'];
                    $res['codeserial'] = $codeserial;
                    $res['created_time'] = date('Y-m-d H:i:s', $value['created_time']);
                    $list[] = $res;
                }
            }
            $data = array('total' => $alarm_list['count'], 'rows' => $list);
            $this->ajaxReturn($data);
        } else {
            $this->display('alarms');
        }

    }


    /**
     * 历史警报信息
     */
    public function alarmlogs($page = 1, $rows = 20, $sort = 'alarm_id', $order = 'desc')
    {
        $alarms_service = Service::instance()->find('common', 'alarms');
        $devices_service = Service::instance()->find('devices', 'devices');
        $type_config = array('1' => '火警', '2' => '低电', '3' => '漏电', '4' => '烟雾', '5' => '高温', '6' => '消防栓开启', '7' => '燃气', '8' => '其他',);
        $disposal_platform_config = array('1' => 'web管理端', '2' => '微信平台', '3' => 'App', '4' => '现场');
        //获取设备类别配置
        $device_categroy_config = $devices_service->getDeviceCategoryConfig();
        $admin_db = D('Usap/Admin/Admin');
        $manager_list = $admin_db->where(['state' => 1])->getField('userid,username');
        if (IS_POST) {
            $request = I('request.');
            $where = 1;
            if ($request['keyword']) {
                $keyword = $request['keyword'];
                $keyword_type = $request['keyword_type'];
                if ($keyword_type == 1) {
                    $where .= " and a.codeserial like '%$keyword%'";
                } elseif ($keyword_type == 2) {
                    $where .= " and c.user_name like '%$keyword%'";
                } else {
                    $where .= " and ( a.codeserial like '%$keyword%' or c.user_name like '%$keyword%')";
                }
            }
            if ($request['start_date']) {
                $start_date = strtotime($request['start_date']);
                $where .= " and a.created_time >= '$start_date'";
            }
            if ($request['end_date']) {
                $end_date = strtotime($request['end_date']);
                $where .= " and a.created_time <= '$end_date'";
            }
            if ($request['alarm_type']) {
                $alarm_type = $request['alarm_type'];
                $where .= " and a.type = '$alarm_type'";
            }
            if ($request['disposal_platform']) {
                $disposal_platform = $request['disposal_platform'];
                $where .= " and a.disposal_platform = '$disposal_platform'";
            }
            $where .= " and a.status =1";
            $alarm_list = $alarms_service->getAlarmsList($where, $page, $rows, $sort, $order);
            $list = [];
            if ($alarm_list['count'] > 0) {
                foreach ($alarm_list['list'] as $value) {
                    $codeserial = $value['codeserial'];
                    $res['alarms_times'] = $value['alarms_times'] ? $value['alarms_times'] : '1';
                    $res['id'] = $value['alarm_id'];
                    $res['type'] = $type_config[$value['type']];
                    $res['user'] = $value['user_name'];
                    $res['disposal_platform'] = $disposal_platform_config[$value['disposal_platform']];
                    $res['device_category'] = $device_categroy_config[$value['device_category']];
                    $res['manager_phone'] = $value['manager_phone'];//可根据实际选取
                    $res['codeserial'] = $codeserial;
                    $res['status'] = $value['status'] == 0 ? '<span style="color: red">未处置</span>' : '<span style="color: green">已处置</span>';
                    $res['device_address'] = $value['device_address'];//设备安装地址
                    $res['created_time'] = date('Y-m-d H:i:s', $value['created_time']);//警报时间
                    $res['updated_time'] = date('Y-m-d H:i:s', $value['updated_time']);//处理时间
                    $list[] = $res;
                }
            }
            $data = array('total' => $alarm_list['count'], 'rows' => $list);
            $this->ajaxReturn($data);
        } else {
            $this->assign('type_config', $type_config);
            $this->assign('disposal_platform_config', $disposal_platform_config);
            $this->display('alarmlogs');
        }

    }


    /**
     * 警报处理
     */
    public function dealAlarms()
    {
        $alarms_service = Service::instance()->find('common', 'alarms');
        $devices_service = Service::instance()->find('devices', 'devices');
        $type_config = array('1' => '火警', '2' => '低电', '3' => '漏电', '4' => '烟雾', '5' => '高温', '6' => '消防栓开启', '7' => '燃气', '8' => '其他',);
        $device_categroy_config = $devices_service->getDeviceCategoryConfig();
        $disposal_platform_config = array('1' => 'web管理端', '2' => '微信平台', '3' => 'App', '4' => '现场');
        $id = I('request.id');
        $alarm_info = $alarms_service->getAlarmsInfoById($id);
        $codeserial = $alarm_info['codeserial'];
        $device_info = $devices_service->getInfoByCodeserial($codeserial);
        $alarm_info['device_category'] = $device_categroy_config[$device_info['device_category']];
        $alarm_info['type'] = $type_config[$alarm_info['type']];
        $admin_db = D('Usap/Admin/Admin');
        $manager_list = $admin_db->where(['state' => 1])->getField('userid,username');
        if (IS_POST) {
            $request = I('request.');
            $alarm_id = $request['id'];
            if (empty($request['disposal_platform'])) {
                $this->error('请选择处理平台');
            }
            if (empty($request['user_id'])) {
                $this->error('请选择处理人');
            }
            $data = [
                'user_id' => $request['user_id'],
                'disposal_platform' => $request['disposal_platform'],
                'remark' => $request['remark'],
                'status' => 1,
                'updated_time' => time(),
            ];
            $res = $alarms_service->updateAlarmsInfo($alarm_id, $data);
            $devices_service->updateDeviceBycodeserial($codeserial, array('is_alarming' => 0));
            if ($res) {
                $data = ['code' => '0000', 'info' => '操作成功'];
                $this->ajaxReturn($data);
            } else {
                $this->error('系统错误,请重试');
            }
        } else {
            $this->assign('alarm_info', $alarm_info);
            $this->assign('manager_list', $manager_list);
            $this->assign('disposal_platform_config', $disposal_platform_config);
            $this->display('deal_alarms');
        }
    }


    /**
     * 地图警报处理
     */
    public function olddealAlarmInfo()
    {
        $request = I('request.');
        $alarms_service = Service::instance()->find('common', 'alarms');
        $codeserial = $request['codeserial'];
        $alarm_type = $request['alarm_type'];
        $alarm_reason = $request['alarm_reason'];
        if (!$codeserial) {
            $this->error('请选择设备');
        }
        $user_id = session('userid');
        $devices_service = Service::instance()->find('devices', 'devices');
        $disposal_platform = $request['disposal_platform'] ? $request['disposal_platform'] : '1';
        $device_info = $devices_service->getInfoByCodeserial($codeserial);
        if (!$device_info) {
            $this->error('设备错误');
        }
        $data = [
            'disposal_platform' => $disposal_platform,
            'status' => 1,
            'user_id' => $user_id,
            'alarm_type' => $alarm_type,
            'remark' => $alarm_reason,
            'updated_time' => time(),
        ];
        $res = $alarms_service->UpdateAlarmsInfoByCodeserial($codeserial, $data);
        if ($res) {
            $data = ['code' => '0000', 'info' => '操作成功'];
            $this->ajaxReturn($data);
        } else {
            $this->error('系统错误,请重试');
        }
    }


    /**
     * 地图警报处理
     */
    public function dealAlarmInfo()
    {
        $request = I('request.');
        $alarms_service = Service::instance()->find('common', 'alarms');
        $codeserial = $request['codeserial'];
        if (!$codeserial) {
            $this->error('请选择设备');
        }
        $user_id = session('userid');
        $devices_service = Service::instance()->find('devices', 'devices');
        $device_info = $devices_service->getInfoByCodeserial($codeserial);
        if (!$device_info) {
            $this->error('设备错误');
        }
        if ($request['data']) {
            $update = [];
            foreach ($request['data'] as $v) {
                $update[] = [
                    'alarm_id' => $v['id'],
                    'disposal_platform' => $v['disposal_platform'],
                    'status' => 1,
                    'user_id' => $user_id,
                    'alarm_type' => $v['alarm_type'],
                    'remark' => $v['remark'],
                    'updated_time' => time(),
                ];
            }
            //批量更新设备
            $res = $alarms_service->dealAlermsInfoByMore($codeserial, $update);
            if ($res) {
                $data = ['code' => '0000', 'info' => '操作成功'];
                $this->ajaxReturn($data);
            } else {
                $this->error('系统错误,请重试');
            }
        } else {
            $this->error('请上报需处置的警报信息');
        }


    }
}
